package com.zh.ssoclient.controller;

import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.core.oidc.user.OidcUser;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class HomeController {
    
    // 首页 - 所有人可访问
    @GetMapping("/")
    public String index() {
        return "index";
    }
    
    // 登录成功后的首页 - 需要认证
    @GetMapping("/home")
    public String home(@AuthenticationPrincipal OidcUser oidcUser, Model model) {
        if (oidcUser != null) {
            // 获取用户信息（使用attributes获取，因为Spring Authorization Server可能使用不同的属性名）
            String username = (String) oidcUser.getAttributes().get("username");
            if (username == null) {
                username = oidcUser.getPreferredUsername();
            }
            
            // 获取邮箱信息
            String email = (String) oidcUser.getAttributes().get("email");
            if (email == null) {
                email = "未提供邮箱信息"; // 设置默认值
            }
            
            // 将用户信息添加到模型中，确保与home.html模板中的属性名匹配
            model.addAttribute("userName", username);
            model.addAttribute("email", email);
            model.addAttribute("sub", oidcUser.getSubject());
        }
        return "home";
    }
    
    // 用户信息页面 - 需要认证
    @GetMapping("/userinfo")
    public String userinfo(@AuthenticationPrincipal OidcUser oidcUser, Model model) {
        if (oidcUser != null) {
            // 获取用户信息
            String username = (String) oidcUser.getAttributes().get("username");
            if (username == null) {
                username = oidcUser.getPreferredUsername();
            }
            
            // 将用户信息添加到模型中
            model.addAttribute("userAttributes", oidcUser.getAttributes());
            model.addAttribute("userAuthorities", oidcUser.getAuthorities());
            model.addAttribute("userName", username);
            model.addAttribute("idToken", oidcUser.getIdToken().getTokenValue());
        }
        return "userinfo";
    }

}